using Digitalmes.Domain.Entities.Mes.Masters;

namespace Digitalmes.Application.Mes.Masters.Workstations.Commands;

/// <summary>
/// 更新工位命令。
/// </summary>
public record UpdateWorkstationCommand(long Id, MdWorkstationDto Workstation) : IRequest<IResult<bool>>;

internal sealed class UpdateWorkstationCommandHandler(IRepository<MdWorkstation> repo) : IRequestHandler<UpdateWorkstationCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(UpdateWorkstationCommand request, CancellationToken cancellationToken)
    {
        // 检查编号是否已存在。
        if (await repo.IsAnyAsync(m => m.WsCode == request.Workstation.WsCode && m.LineId == request.Workstation.LineId && m.Id != request.Id, cancellationToken))
        {
            return Result.Failure("工站编号已存在");
        }

        var workstation = await repo.GetByIdAsync(request.Id, cancellationToken);
        if (workstation == null)
        {
            return Result.Failure("未找到要更新的工站");
        }

        workstation.WsName = request.Workstation.WsName;
        workstation.WsType = request.Workstation.WsType;
        workstation.Order = request.Workstation.Order;
        workstation.Status = request.Workstation.Status;

        var ok = await repo.UpdateAsync(workstation, m => new
        {
            m.WsName,
            m.WsType,
            m.Order,
            m.Status,
            m.UpdatedBy,
            m.UpdatedTime,
        }, cancellationToken);
        return Result.From(ok);
    }
}
